package org.zjsru.order.config;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

public class LoadBalancerConfig {

    //自定义负载均衡策略，随机
/*    @Bean
    public ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
                                                                    LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new RandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
    }*/
    //自定义负载均衡策略，轮询

    /**
     * 配置RoundRobin算法的负载均衡器
     * 该方法通过Spring的@Bean注解定义了一个Bean，类型为ReactorLoadBalancer，用于在服务实例间进行负载均衡
     * 它使用了环境属性和负载均衡客户端工厂来创建一个轮询算法的负载均衡器
     *
     * @param environment               包含环境属性的Environment对象，用于获取负载均衡客户端工厂的属性
     * @param loadBalancerClientFactory 负载均衡客户端工厂，用于获取服务实例列表供应商
     * @return 返回一个配置了RoundRobin算法的负载均衡器实例
     */
/*    @Bean
    public ReactorLoadBalancer<ServiceInstance> roundRobinLoadBalancer(Environment environment,
                                                                       LoadBalancerClientFactory loadBalancerClientFactory) {
        // 从环境属性中获取负载均衡客户端工厂的名称属性
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        // 使用获取的名称属性和服务实例列表供应商创建并返回一个RoundRobinLoadBalancer实例
        return new RoundRobinLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
    }*/
    @Bean
    // 自定义负载均衡策略，随机
    public ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
                                                                   LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        return new RandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
    }
}
